package com.zkingsoft.command.impl;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zkingsoft.command.AbstractCommand;

public class CreateCodeCommandImpl extends AbstractCommand {

	private final char[] codes = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','0','1','2','3','4','5','6','7','8','9'};
	
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("image/png");//将响应格式设置为图片内容得响应格式
		
		//生成验证码字符内容
		char[] validateCode = new char[4];
		Random random = new Random();
		for(int i = 0; i < validateCode.length; i++) {
			validateCode[i] = codes[random.nextInt(codes.length)];
		}
		HttpSession session = request.getSession(true);
		session.setAttribute("ValidateCode", new String(validateCode));//验证码保存到Session中，方便后期进行验证码校验
		
		BufferedImage image = new BufferedImage(100,46,BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();//生成绘图对象
		
		g.fillRect(0, 0, 100, 46);//画一个矩形
		g.setColor(Color.RED);
		g.drawRect(0, 0, 100, 46);
		//加干扰线
		for(int i = 0; i < 10; i++) {
			int x1 = random.nextInt(100);
			int y1 = random.nextInt(46);
			int x2 = random.nextInt(100);
			int y2 = random.nextInt(46);
			g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
			g.drawLine(x1, y1, x2, y2);
		}
		
		g.setFont(new Font("黑体",Font.ITALIC,28));
		for(int i = 0; i < validateCode.length; i++) { 
			g.setColor(new Color(random.nextInt(255),
										random.nextInt(255),
											random.nextInt(255)));
			g.drawString(String.valueOf(validateCode[i]), 
								20 * i + 4, 
									25);//画一段文字
		}
		//将BufferedImage基于outputStream输出
		ImageIO.write(image, "png", response.getOutputStream());
	}

}
